import 'dart:async';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/language.dart';
import 'package:bike_ride/common/util/model_utils.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/tool_tip_painter.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/wallet/model/recharge_info_m.dart';
import 'package:bike_ride/model/wallet/view_model/wallet_vm.dart';
import 'package:bike_ride/res/IconFont.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pretty_qr_code/pretty_qr_code.dart';

///钱包页
class WalletView extends BaseStatefulPage<WalletViewModel> {
  // show_charge_dialog
  final Map<String,dynamic>? arguments;

  const WalletView({super.key,this.arguments});

  @override
  WalletViewState createState() => WalletViewState();
}

class WalletViewState
    extends BaseStatefulPageState<WalletView, WalletViewModel> {
  final erCodeKey = GlobalKey();

  late Timer timer;
  int _countdown = 0;

  void dismissErCodeDialog(){
    final keyStateMounted = erCodeKey.currentState?.mounted??false;
    if(keyStateMounted || viewModel!.fiuuPayM != null){
      Navigator.pop(context);
    }
  }

  @override
  void initAttribute() {
    timer = Timer.periodic(const Duration(seconds: 2), (timer) {
      final keyStateMounted = erCodeKey.currentState?.mounted??false;
      //定时请求次数30次
      if(keyStateMounted || viewModel!.startTimer){
        if(_countdown < 30){
          _countdown++;
          viewModel!.getOverseasPayStatus();
        }else{
          EasyLoading.showError(S.current.payOverTime);
          Navigator.pop(context);
        }
      }else{
        _countdown = 0;
      }
    });
  }

  @override
  void initObserver() {}

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  WalletViewModel viewBindingViewModel() {
    return WalletViewModel()..viewState = this;
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        children: [
          PageTitleWidget(title: S.current.myWallet),
          Padding(
            padding: EdgeInsets.symmetric(
                horizontal: ThemeStyles.pagePaddingHorizontal),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildContainer1(),
                SizedBox(
                  height: 16.rpx,
                ),
                if(!hideRecharge)
                  ...[
                    XbButton(
                        width: MediaQuery.of(context).size.width -
                            2 * ThemeStyles.pagePaddingHorizontal,
                        height: 96.rpx,
                        hasBorder: true,
                        isDefault: true,
                        borderColor: Theme.of(context).colorScheme.primary,
                        color: ColorStyles.color_FFFFFF,
                        onPressed: () {
                          showRechargeDialog();
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              IconFont.iconrecharge,
                              size: 36.rpx,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                            Text(
                              S.current.recharge,
                              style: TextStyle(
                                  color: Theme.of(context).colorScheme.primary,
                                  fontSize: 32.rpx),
                            )
                          ],
                        )),
                    SizedBox(
                      height: 32.rpx,
                    ),
                    _buildRowWidget(
                        const Color(0xFFFF8D1A),
                        IconFont.iconVectordefuben2,
                        S.current.myDeposit,
                        Text(
                          S.current.unNeedDepositArea,
                          style: const TextStyle(color: ColorStyles.color_848F99),
                        ), () {
                      //nothing
                    }),
                    SizedBox(
                      height: 16.rpx,
                    ),
                  ],
                _buildRowWidget(
                    const Color(0xFFFF4242),
                    IconFont.iconpaydetail,
                    S.current.tradeDetail,
                    Icon(
                      IconFont.iconjiantouyou,
                      size: 32.rpx,
                      color: ColorStyles.color_848F99,
                    ), () {
                  NavigatorUtil.push(context, Routers.transactionsPage);
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContainer1() {
    return GestureDetector(
      onTap: () {
        NavigatorUtil.push(context, Routers.latelyRechargeView).then((value) {
          if (value != null) {
            viewModel!.getRefundInfo();
          }
        });
      },
      child: Container(
        width: MediaQuery.of(context).size.width -
            2 * ThemeStyles.pagePaddingHorizontal,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24.rpx),
          gradient: LinearGradient(colors: [
            ColorStyles.color_gradient_start,
            Theme.of(context).colorScheme.primary,
          ]),
        ),
        child: Stack(
          children: [
            Column(
              children: [
                SizedBox(
                  height: 24.rpx,
                ),
                Text(
                  S.current.walletBalance,
                  style: TextStyle(
                      color: ColorStyles.color_FFFFFF,
                      fontSize: 28.rpx,
                      fontWeight: FontWeight.w500),
                ),
                SizedBox(
                  height: 32.rpx,
                ),
                Text(
                  '${parseToMoney(((viewModel!.discountStatM?.balanceAmount??0)+(viewModel!.discountStatM?.giftBalanceAmount??0)))}',
                  style: TextStyle(
                      color: ColorStyles.color_FFFFFF,
                      fontSize: 64.rpx,
                      fontWeight: FontWeight.bold),
                ),
                Container(
                  constraints: BoxConstraints(minHeight: 72.rpx),
                  color: ColorStyles.color_FFFFFF.withOpacity(0.14),
                  padding: EdgeInsets.only(left: 32.rpx,top: 8.rpx,bottom: 8.rpx,right: 32.rpx),
                  margin: EdgeInsets.only(top: 30.rpx),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '${S.current.rechargeAmount}：${parseToMoney(viewModel!.discountStatM?.balanceAmount)}${S.current.yuan}',
                            style: TextStyle(
                                color: ColorStyles.color_FFFFFF,
                                fontSize: 28.rpx,
                                fontWeight: FontWeight.w500),
                          ),
                          const Spacer(),
                          if(Language.isZh)
                            _buildZhChild(),
                        ],
                      ),
                      if(!Language.isZh)
                        _buildZhChild(),
                    ],
                  ),
                )
              ],
            ),
            if (viewModel!.refundInfoM?.id != null)
              Positioned(
                left: 120.rpx,
                bottom: 80.rpx,
                child: CustomPaint(
                  painter: TooltipPainter(
                      arrowPosition: 72.rpx,
                      ap: AlignPosition.bottom,
                      color: ColorStyles.color_FF5500),
                  child: Container(
                    padding: EdgeInsets.symmetric(
                        vertical: 4.rpx, horizontal: 8.rpx),
                    child: Text(
                      S.current.applyRefunding,
                      style: TextStyle(
                          color: ColorStyles.color_FFFFFF, fontSize: 24.rpx),
                    ),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }

  Widget _buildZhChild(){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '${S.current.giftAmount}：${parseToMoney(viewModel!.discountStatM?.giftBalanceAmount)}${S.current.yuan}',
            style: TextStyle(
                color: ColorStyles.color_FFFFFF,
                fontSize: 28.rpx,
                fontWeight: FontWeight.w500),
          ),
          Icon(
            Icons.help_outline_rounded,
            size: 28.rpx,
            color: ColorStyles.color_FFFFFF,
          )
        ],
      ),
      onTap: (){
        showAlertDialog(
          context: context,
          contentTxt: S.current.giftAmountDesc,
          hasCancel: false,
          confirmName: S.current.known,
          onConfirm: () {
            Navigator.of(context).pop();
          },
        );
      },
    );
  }
  Widget _buildRowWidget(Color bgColor, IconData iconData, String title,
      Widget right, Function() onPress) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onPress,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 24.rpx, horizontal: 32.rpx),
        decoration: BoxDecoration(
            color: ColorStyles.color_FFFFFF,
            borderRadius: BorderRadius.all(Radius.circular(16.rpx))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              height: 64.rpx,
              width: 64.rpx,
              decoration: BoxDecoration(
                  color: bgColor.withOpacity(0.2),
                  borderRadius: BorderRadius.all(Radius.circular(16.rpx))),
              child: Center(
                child: Icon(
                  iconData,
                  size: 32.rpx,
                  color: bgColor,
                ),
              ),
            ),
            SizedBox(
              width: 16.rpx,
            ),
            Text(
              title,
              style: TextStyle(fontSize: 32.rpx),
            ),
            const Spacer(),
            right,
          ],
        ),
      ),
    );
  }

  bool get hideRecharge => viewModel?.rechargeInfoM?.rechargeList == null || viewModel!.rechargeInfoM!.rechargeList!.isEmpty;
  void showRechargeDialog() {
    if(hideRecharge){
      return;
    }

    showModalBottomSheet<bool?>(
      context: context,
      // backgroundColor: Colors.transparent,
      isScrollControlled: true,
      // barrierColor: Colors.black.withOpacity(0.2),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.rpx),
          topRight: Radius.circular(20.rpx),
        ),
      ),
      builder: (context) => _DialogBuilder(
        viewModel: viewModel!,
        model: viewModel!.rechargeInfoM,
      ),
    );
  }

  void navigateToPayView(String payApi) async{
    NavigatorUtil.push(context, Routers.webViewPage,arguments: {
      'url': payApi,
    }).then((_){
      viewModel!.getOverseasPayStatus().then((value){
        if(value == false){
          viewModel!.startTimer = true;
        }
      });
    });
  }

  void showPayErCodeDialog(){
    showAlertDialog(
      context: context,
      title: S.current.pleasePaySco,
      confirmName: S.current.mePayed,
      cancelName: S.current.dealLater,
      onWillPopBol: false, //避免手机误触，退出支付二维码
      content: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(14.rpx),
        ),
        child: Center(
            child: PrettyQr(
              key: erCodeKey,
              data: viewModel!.overseasPayM!.qrCode!.split('code=').last,
              size: 400.rpx,
              errorCorrectLevel: QrErrorCorrectLevel.H,
              roundEdges: true,
            )),
      ),
      onCancel: () {
        viewModel!.overseasPayM = null;
        EasyLoading.showToast(S.current.payNoFinish);
        Navigator.of(context).pop();
      },
      onConfirm: () {
        viewModel!.getOverseasPayStatus().then((value) {
          if(value){
            Navigator.of(context).pop();
            Future.delayed(const Duration(milliseconds: 500),(){
              Navigator.of(context).pop();
            });
          }else{
            EasyLoading.showError(S.current.payResponse1);
          }
        });
      },
    );
  }
}

class _DialogBuilder extends StatefulWidget {
  final RechargeInfoM? model;
  final WalletViewModel viewModel;

  const _DialogBuilder({this.model, required this.viewModel});

  @override
  State<_DialogBuilder> createState() => _DialogBuilderState();
}

class _DialogBuilderState extends State<_DialogBuilder> {
  final tapGestureRecognizer = TapGestureRecognizer();

  int selectedIndex = 0;
  bool protocolChecked = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(40.rpx),
          topRight: Radius.circular(40.rpx),
        ),
        color: Colors.white,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            height: 80.rpx,
            child: Stack(
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: IconButton(
                    icon: Icon(
                      IconFont.iconclosel,
                      size: 32.rpx,
                      color: ColorStyles.color_333333,
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                Center(
                  child: Text(
                    S.current.rechargeOptions,
                    style: TextStyle(
                        fontSize: 32.rpx, color: ColorStyles.color_000000),
                  ),
                )
              ],
            ),
          ),
          const Divider(
            color: ColorStyles.color_F5F5F5,
          ),
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: ThemeStyles.pagePaddingHorizontal,
            ),
            constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.6),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    S.current.selectRechargeAmount,
                    style: TextStyle(
                        fontSize: 28.rpx, color: ColorStyles.color_333333),
                  ),
                  if(widget.model!.rechargeList!.isNotEmpty)
                    GridView.count(
                      crossAxisCount: 3,
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      padding: EdgeInsets.symmetric(vertical: 8.rpx),
                      mainAxisSpacing: 8.rpx,
                      crossAxisSpacing: 8.rpx,
                      childAspectRatio: 1.35,
                      children: [
                        for (int i = 0;
                            i < widget.model!.rechargeList!.length;
                            i++)
                          _buildItem(i),
                      ],
                    ),
                  Text(
                    S.current.walletTips,
                    style: TextStyle(
                        fontSize: 24.rpx, color: ColorStyles.color_999999),
                  ),
                ],
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: ColorStyles.color_FFFFFF,
              boxShadow: [
                BoxShadow(
                  color: ColorStyles.color_CC646464.withOpacity(0.2),
                  blurRadius: 4.rpx,
                  offset: Offset(0, -8.rpx),
                )
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 24.rpx,
                    ),
                    constraints: BoxConstraints(
                      minHeight: 30.rpx,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          protocolChecked
                              ? Icons.check_circle_outline_outlined
                              : Icons.radio_button_unchecked_outlined,
                          size: 28.rpx,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        SizedBox(width: 8.rpx,),
                        Flexible(
                          child: RichText(
                            text: TextSpan(
                                children: [
                                  TextSpan(text: S.current.check),
                                  TextSpan(
                                      text:
                                          '《${S.current.rechargeOrPayProtocol}》',
                                      style: TextStyle(
                                          color: Theme.of(context)
                                              .colorScheme
                                              .primary,
                                          fontSize: 28.rpx),
                                      recognizer: tapGestureRecognizer
                                        ..onTap = () {
                                          NavigatorUtil.push(
                                              context, Routers.webViewPage,
                                              arguments: {
                                                'url': AccountManager
                                                    .payProtocolUrl,
                                              });
                                        }),
                                  TextSpan(text: S.current.andConfirm),
                                ],
                                style: TextStyle(
                                    color: ColorStyles.color_333333,
                                    fontSize: 28.rpx)),
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: (){
                    setState(() {
                      protocolChecked = !protocolChecked;
                    });
                  },
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    XbButton(
                      width: MediaQuery.of(context).size.width -
                          2 * ThemeStyles.pagePaddingHorizontal,
                      isDefault: false,
                      child: Text('${S.current.payConfirm} ${widget.model!.rechargeList![selectedIndex]} ${S.current.yuan}'),
                      onPressed: () {
                        if(!protocolChecked){
                          EasyLoading.showInfo(S.current.readProtocol);
                          return;
                        }
                        widget.viewModel.getOverseasOpenPay(
                            widget.model!.rechargeList![selectedIndex]);
                        // num payChanel;
                        // if(EnvConfig.payChanelByMPT){
                        //   payChanel = 13;
                        // }else{
                        //   //默认马来fiuu支付
                        //   payChanel = 12;
                        // }
                        // widget.viewModel.getOverseasH5Pay(
                        //     widget.model!.rechargeList![selectedIndex],payChanel: payChanel);
                      },
                    )
                  ],
                ),
                SizedBox(
                  height: 32.rpx,
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildItem(int index) {
    bool isSelected = index == selectedIndex;
    final texStyle = TextStyle(
        fontSize: 40.rpx,
        color: isSelected ? ColorStyles.color_FFFFFF : ColorStyles.color_0A1B29,
        fontWeight: FontWeight.bold);

    final themeColor = Theme.of(context).colorScheme.primary;
    final totalHeight = 200.rpx;
    final bottomHeight = 50.rpx;
    final isGiftAmountShow = (widget.model!.giftAmountList != null && widget.model!.giftAmountList!.isNotEmpty) && widget.model!.giftAmountList?[index] != null &&
        widget.model!.giftAmountList![index] > 0;

    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
      child: Container(
        width: totalHeight,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(18.rpx)),
            border: Border.all(color: themeColor)),
        child: Stack(
          children: [
            Positioned(left: 0,right: 0,top: 0,bottom: isGiftAmountShow?bottomHeight:0,child: Container(
              decoration: BoxDecoration(
                color: isSelected?themeColor: ColorStyles.color_FFFFFF,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(16.rpx),
                    topRight: Radius.circular(16.rpx),
                  bottomLeft: Radius.circular(isGiftAmountShow?0:16.rpx),
                  bottomRight: Radius.circular(isGiftAmountShow?0:16.rpx)
                ),
              ),
            ),),
            Center(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('￥', style: texStyle.copyWith(fontSize: 24.rpx)),
                  Text('${widget.model!.rechargeList![index]}', style: texStyle)
                ],
              ),
            ),
            if (isGiftAmountShow)
              Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: bottomHeight,
                  color: themeColor.withOpacity(0.2),
                  child: Center(
                    child: Text(
                      '${S.current.gift} ${widget.model!.giftAmountList![index]} ${S.current.yuan}',
                      style: TextStyle(color: themeColor, fontSize: 24.rpx),
                    ),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }
}
